package com.ajk.server.security;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.util.Assert;

import com.ajk.server.exception.ErrorConstant;


public class AjkAuthenticationEntryPoint implements AuthenticationEntryPoint {
	private static Logger loggerFilter = LoggerFactory.getLogger("authentication_filter");
    
    private String realmName;

    public void afterPropertiesSet() throws Exception {
        Assert.hasText(realmName, "realmName must be specified");
    }

    private void writeLog(HttpServletRequest request,Integer errorCode,Object signature,Object stringToSign){
    	StringBuilder sb = new StringBuilder();
    	if(request!=null){
    		sb.append("requestUrl:").append(request.getRequestURI()).append("\n");
    		sb.append("Device-Type:").append(request.getHeader("Device-Type")).append("\n");
    		sb.append("APP-Ver:").append(request.getHeader("APP-Ver")).append("\n");
    		sb.append("Authorization:").append(request.getHeader("Authorization")).append("\n");
    		sb.append("Date:").append(request.getHeader("Date")).append("\n");
    		sb.append("Method:").append(request.getMethod()).append("\n");
    		sb.append("ContentType:").append(request.getContentType()).append("\n");
    		if(signature!=null)
    			sb.append("signature:").append(signature).append("\n");
     		if(stringToSign!=null)
    			sb.append("stringToSign:\n").append(stringToSign).append("\n");
    		sb.append("errorCode:").append(errorCode).append("\n\n");
    	}
    	loggerFilter.info(sb.toString());
    }
    
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
        throws IOException, ServletException {
        response.addHeader("WWW-Authenticate", "Basic realm=\"" + realmName + "\"");
        
        if  (authException instanceof AccountExpiredException) {
        	writeLog(request,ErrorConstant.ACCOUNT_EXPIRED.getErrorCode(),request.getAttribute("signature"),request.getAttribute("stringToSign"));
            response.sendError(ErrorConstant.ACCOUNT_EXPIRED.getErrorCode(), ErrorConstant.ACCOUNT_EXPIRED.getMsg());
        } else if  (authException instanceof CredentialsExpiredException) {
        	writeLog(request,ErrorConstant.CREDENTIALS_EXPIRED.getErrorCode(),request.getAttribute("signature"),request.getAttribute("stringToSign"));
            response.sendError(ErrorConstant.CREDENTIALS_EXPIRED.getErrorCode(), authException.getMessage());
        }else{
        	writeLog(request,ErrorConstant.UNAUTHORIZED.getErrorCode(),request.getAttribute("signature"),request.getAttribute("stringToSign"));
        	response.sendError(ErrorConstant.UNAUTHORIZED.getErrorCode(), authException.getMessage());
        }
    }

    public String getRealmName() {
        return realmName;
    }

    public void setRealmName(String realmName) {
        this.realmName = realmName;
    }
}
